﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Adalbertus.BudgetPlanner.Extensions;
using Adalbertus.BudgetPlanner.ViewModels;
using Caliburn.Micro;
using Castle.Windsor;

namespace Adalbertus.BudgetPlanner
{
    /// <summary>
    /// http://www.iamnotmyself.com/2010/07/31/AnImplementationOfCastleWindsorBootstrapperForCaliburnMicro.aspx
    /// </summary>
    public class CastleBootstrapper : Bootstrapper<ShellViewModel>
    {
        private IWindsorContainer container;

        protected override void Configure()
        {
            container = new ApplicationContainer();
        }

        //protected override void DisplayRootView()
        //{
        //    var viewModel = IoC.Get<IShell>();
        //    IWindowManager windowManager;

        //    try
        //    {
        //        windowManager = IoC.Get<IWindowManager>();
        //    }
        //    catch
        //    {
        //        windowManager = new WindowManager();
        //    }

        //    windowManager.ShowDialog(viewModel);
        //    //base.DisplayRootView();
        //}

        protected override object GetInstance(Type service, string key)
        {
            object result = null;
            if (string.IsNullOrWhiteSpace(key))
            {
                result = container.Resolve(service);
            }
            else
            {
                result = container.Resolve(key, service);
            }

            return result;
        }

        protected override IEnumerable<Assembly> SelectAssemblies()
        {
            var execAssembly = Assembly.GetExecutingAssembly();
            var viewModels = Assembly.LoadFrom("Adalbertus.BudgetPlanner.ViewModels.dll");
            var views = Assembly.LoadFrom("Adalbertus.BudgetPlanner.Views.dll");
            return new[]
                        {
                            Assembly.GetExecutingAssembly(),
                            viewModels,
                            views
                        };

        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            var result = (IEnumerable<object>)container.ResolveAll(service);
            return result;
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }
    }
}
